//
//  AffirmOrderController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/5/5.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "AffirmOrderController.h"
#import "FinishedViewController.h"
#import "ZYQAssetPickerController.h"
#import "UIActionSheet+Blocks.h"
#import "MWPhotoBrowser.h"
#import "UpLoadImageManager.h"

@interface AffirmOrderController ()<ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,MWPhotoBrowserDelegate>
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *ImageBtnArray;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *line1;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *line2;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
@property (strong,nonatomic) NSMutableArray *imageArry;
@property (nonatomic, strong) NSMutableArray *photos;
@property (strong,nonatomic) NSMutableArray *postArray;

@end

@implementation AffirmOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"确认订单";
    [self addBackButton];
    self.numberLabel.text = @"上传服务证明，您必须要上传3张照片";
    self.imageArry = [NSMutableArray array];
    self.postArray = [NSMutableArray array];
    if (ScreenWidth == 320) {
        self.line1.constant = self.line2.constant = 13.0f;
    }
    __weak typeof(self)weakSelf = self;
    [self addRightButtonWithTitle:@"完成" actionBlock:^{
        if (weakSelf.imageArry.count < 3) {
            [SVProgressHUD showErrorWithStatus:@"必须上传3张洗车照片"];
        } else {
            weakSelf.postArray = [NSMutableArray array];
            [UpLoadImageManager uploadImage:weakSelf.imageArry[0] uploadImageURL:KWashCarImageInterface withCompltedBlock:^(BOOL success, NSString *urlString) {
                if (success) {
                    NSLog(@"洗车照片：%@",urlString);
                    [weakSelf.postArray addObject:urlString];
                    [UpLoadImageManager uploadImage:weakSelf.imageArry[1] uploadImageURL:KWashCarImageInterface withCompltedBlock:^(BOOL success, NSString *urlString) {
                        if (success) {
                            NSLog(@"洗车照片：%@",urlString);
                            [weakSelf.postArray addObject:urlString];
                            [UpLoadImageManager uploadImage:weakSelf.imageArry[2] uploadImageURL:KWashCarImageInterface withCompltedBlock:^(BOOL success, NSString *urlString) {
                                if (success) {
                                    NSLog(@"洗车照片：%@",urlString);
                                    [weakSelf.postArray addObject:urlString];
                                    [weakSelf webRequest_GetOrderInfo];
                                }else{
                                    
                                    
                                }
                            }];}
                    }];}
            }];
        }
    }];
}

#pragma mark -- 网络请求 --
-(void)webRequest_GetOrderInfo
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"正在加载...";
    [self.view addSubview:hud];
    [hud show:YES];
    __weak typeof(self)weakself = self;
    NSDictionary *dict = @{@"sn":self.orderSN,@"wash_pic1":self.postArray[0],@"wash_pic2":self.postArray[1],@"wash_pic3":self.postArray[2]};
    [HttpRequestManager getMethod:KConfirOrderInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            FinishedViewController *finishVC = [[FinishedViewController alloc]init];
            [weakself.navigationController pushViewController:finishVC animated:YES];
    
        }else{
            
        }
    }];
}



- (IBAction)updataImageButtonAction:(UIButton *)sender
{
    
    if(self.imageArry.count <= sender.tag)
    {
        if(sender.tag > self.imageArry.count)
        {
            
        }else{
            [self AssetPickerView];
        }
    }else{
        [self didSmallImageToBigImage_Action:self.imageArry setNumber:sender.tag];
    }
}


-(void)AssetPickerView
{
    __weak typeof(self)weakSelf = self;
    RIButtonItem *takePhotoButton = [RIButtonItem itemWithLabel:@"拍照" action:^{
        [weakSelf SetPhotoView:self.imageArry.count setWitchSelect:YES];
    }];
    RIButtonItem *choosePhotoButton = [RIButtonItem itemWithLabel:@"从相册选取" action:^{
        [weakSelf SetPhotoView:self.imageArry.count setWitchSelect:NO];
        
    }];
    UIActionSheet *imageSourcePickActionSheet;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:takePhotoButton,choosePhotoButton,nil];
    }else{
        imageSourcePickActionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" cancelButtonItem:nil destructiveButtonItem:[RIButtonItem itemWithLabel:@"取消"] otherButtonItems:choosePhotoButton,nil];
    }
    [imageSourcePickActionSheet showInView:weakSelf.view];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self.imageArry addObject:image];
    [picker dismissViewControllerAnimated:YES completion:^{
        [self setBtnImage:self.imageArry];
    }];
}

-(void)SetPhotoView:(NSInteger)count setWitchSelect:(BOOL)type
{
    if(type){
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else{
        ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
        picker.maximumNumberOfSelection = 3-count;
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups=NO;
        picker.delegate=self;
        picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                return duration >= 3;
            } else {
                return YES;
            }
        }];
        [self presentViewController:picker animated:YES completion:NULL];
    }
}

#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    for (int i = 0; i<assets.count; i++) {
        ALAsset *asset = assets[i];
        UIImage* image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [self.imageArry addObject:image];
    }
    [self setBtnImage:self.imageArry];
}

-(void)setBtnImage:(NSMutableArray *)imagearray
{
    self.numberLabel.text = [NSString stringWithFormat:@"您还要上传%lu张照片",3 - imagearray.count];
    for (int i = 0; i<3; i++) {
        UIButton *sender = self.ImageBtnArray[i];
        [sender setBackgroundImage:[UIImage imageNamed:@"添加图片"] forState:UIControlStateNormal];
    }
    for (int i = 0; i<self.imageArry.count; i++) {
        UIButton *sender = self.ImageBtnArray[i];
        [sender setBackgroundImage:imagearray[i] forState:UIControlStateNormal];
    }
    if(imagearray.count < 3){
        UIButton *sender = self.ImageBtnArray[imagearray.count];
        [sender setBackgroundImage:[UIImage imageNamed:@"添加图片框"] forState:UIControlStateNormal];
    }
}

-(void)didSmallImageToBigImage_Action:(NSMutableArray *)imageArray setNumber:(NSInteger)nub
{
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    BOOL displayActionButton = YES;
    BOOL displaySelectionButtons = NO;
    BOOL displayNavArrows = NO;
    BOOL enableGrid = YES;
    BOOL startOnGrid = NO;
    for (int i = 0; i<imageArray.count; i++) {
        photo = [MWPhoto photoWithImage:imageArray[i]];
        photo.caption = @"";
        [photos addObject:photo];
        enableGrid = NO;
    }
    self.photos = photos;
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = displayActionButton;
    browser.displayNavArrows = displayNavArrows;
    browser.displaySelectionButtons = displaySelectionButtons;
    browser.alwaysShowControls = displaySelectionButtons;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = enableGrid;
    browser.startOnGrid = startOnGrid;
    browser.enableSwipeToDismiss = YES;
    [browser setCurrentPhotoIndex:nub];
    [self.navigationController pushViewController:browser animated:YES];

}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}

- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index
{
    MWPhoto *photo = [self.photos objectAtIndex:index];
    MWCaptionView *captionView = [[MWCaptionView alloc] initWithPhoto:photo];
    //    UIView * button = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    //    [button setBackgroundColor:[UIColor whiteColor]];
    //    [captionView addSubview:button];
    return captionView;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
    NSLog(@"Did start viewing photo at index %lu", (unsigned long)index);
}

-(void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index {
    if(self.photos.count == 1)
    {
        [self.photos removeObjectAtIndex:index];
        [self.imageArry removeObjectAtIndex:index];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.photos removeObjectAtIndex:index];
        [self.imageArry removeObjectAtIndex:index];
        [photoBrowser reloadData];
    }
    [self setBtnImage:self.imageArry];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
